package com.qf.shop.auth.shop10auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Date;

// JWT(JSON Web Token)
public class JwtDemo {

    public static void main(String[] args) {

        // 实际返回用户的数据
        String name = "赵莉";

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, 30);

        // 1.使用JWT生成一个Token(字符串)
        JWTCreator.Builder builder = JWT.create();
        String token = builder
                .withClaim("name", name)
                .withClaim("age", 20)
                .withExpiresAt(calendar.getTime()) // 生成token的过期时间是30s
                .sign(Algorithm.HMAC256("2103-shop"));
        System.out.println(token);

        String reqToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi6LW16I6JIiwiZXhwIjoxNjI4NjY4NTkzLCJhZ2UiOjIwfQ.ERVqRL1mrtMoA9Tgk_i3FzcaleHAYZQJTA8jd9DtaUs";
        // 校验
        Verification verification = JWT.require(Algorithm.HMAC256("2103-shop"));
        try {
            DecodedJWT verify = verification.build().verify(reqToken);// 在做对比的时候服务端存Tokne了吗？
            System.out.println("校验成功");
            String name1 = verify.getClaim("name").asString();
            int age = verify.getClaim("age").asInt();
            String age1 = verify.getClaim("age").asString(); // 取决于设置时数据类型
            System.out.println("name1:" + name1);
            System.out.println("age:" + age);
            System.out.println("age1:" + age1);
        } catch (SignatureVerificationException e) {
            System.out.println("token验证失败了，签名不一致");
        } catch (AlgorithmMismatchException e) {
            System.out.println("token验证失败了，签名算法不一致");
        } catch (TokenExpiredException e) {
            System.out.println("token验证失败了，token过期了");
        }

    }
}
